<template>
  <div>
    <a-card size="small">
      <div slot="title" class="flx-b">
        <div>{{ title }}</div>
        <div>
          <a-button v-if="val.length===0" shape="circle" class="mr10" @click="init"><i class="fa fa-plus"/></a-button>
          <a-button shape="circle" @click="ok"><i class="fa fa-check"/></a-button>
        </div>
      </div>
      <div v-for="(v,i) in val" :key="i" class="mb10 flx-s">
        <a-input class="mr10" placeholder="key" v-model.trim="v.key"></a-input>
        <a-input class="mr10" placeholder="value" v-model.trim="v.value"></a-input>
        <div class="flx-c btn mr10" @click="plus(i)"><i class="fa fa-plus-circle"/></div>
        <div class="flx-c btn" @click="minus(i)"><i class="fa fa-minus-circle"/></div>
      </div>
    </a-card>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'modelVal',
    event: 'change'
  },
  props: {
    modelVal: {
      type: Array,
      default: () => {
        return []
      }
    },
    title: {
      type: String,
      default: 'KV编辑器'
    }
  },
  data () {
    return {
      val: []
    }
  },
  mounted () {
    this.val = this.modelVal
  },
  watch: {
    modelVal (v) {
      this.val = v
    },
    val (v) {
      this.$emit('change', v)
    }
  },
  methods: {
    init () {
      if (this.val.length === 0) {
        this.val.push({ key: '', value: '' })
      }
    },
    plus (i) {
      this.val.splice(i + 1, 0, { key: '', value: '' })
    },
    minus (i) {
      this.val.splice(i, 1)
    },
    ok () {
      const step1Arr = this.val.filter(t => {
        return t.key.length > 0 && t.value.length > 0
      })
      const step2Arr = []
      step1Arr.forEach(t1 => {
        if (step2Arr.some(t2 => t2.key === t1.key)) {
          console.log(t1.key + '重复')
        } else {
          step2Arr.push({ key: t1.key, value: t1.value })
        }
      })
      // this.$success({ title: '完成数据检查' })
      this.val = step2Arr
    }
  }
}
</script>
<style lang="scss" scoped>
.btn{
  .fa{
    font-size:24px;
    cursor:pointer;
    &:hover{
      color:#2979ff;
    }
  }
}
</style>
